package org.flexlancer.managers
{
	import flash.geom.Rectangle;
	
	import mx.core.UIComponent;
	
	import org.flexlancer.interfaces.ISelectableItem;
	
	public class SelectionManager
	{
		private static var selectionObjects:Array = new Array();
		
		public static function ClearSelections():void{
			try{
				for each ( var imsg:ISelectableItem in selectionObjects ){
					imsg.Selected = false;
				}
				selectionObjects = new Array;
			}catch(err:Error){
				throw err;
			}
		}
		
		public static function get moreThan2Selection ():Boolean{
			try{
				if ( selectionObjects.length > 2 ) return true;
				else return false;
			}catch(err:Error){
				throw err;
			}
			return false;
		}
		
		public static function AddSelection(parmItem:ISelectableItem):void{
			try{
				if ( moreThan2Selection ){
					ClearSelections();
				}else if (selectionObjects.length == 2 ){
					ISelectableItem(selectionObjects[0]).Selected = false;
					selectionObjects.splice(0,1);
				}
				parmItem.Selected = true;
				selectionObjects.push(parmItem);
			}catch(err:Error){
				throw err;
			}
		}
		
		public static function AddSelectionRange(parmArrObj:Array):void{
			try{
				ClearSelections();
				selectionObjects = parmArrObj;
				for each ( var imsg:ISelectableItem in selectionObjects ){
					imsg.Selected = true;
				}
			}catch(err:Error){
				throw err;
			}
		}
		
		public static function get SelectedItems():Array{
			return selectionObjects;
		}
		
		public static function get SelectedItem():ISelectableItem{
			return selectionObjects[0];
		}
		
		public static function get SelectionRectangle():Rectangle{
			try{
				var rect:Rectangle = null ; 
				
				for each ( var sItem:UIComponent in selectionObjects ){
					
					if ( rect == null ){
						rect = new Rectangle( sItem.x , sItem.y , sItem.width , sItem.height );
						continue;
					}
					
					if ( rect.x > sItem.x ){
						rect.width += Math.abs(rect.x - sItem.x);
						rect.x = sItem.x;
					}
					
					if ( rect.y > sItem.y ){
						rect.height += Math.abs(rect.y - sItem.y);
						rect.y =  sItem.y;
					}
					
					if ( (rect.x + rect.width) < (sItem.x + sItem.width) ){
						rect.width =  (sItem.x + sItem.width - rect.x);
					}
					
					if (  (rect.y + rect.height) < (sItem.y + sItem.height) ){
						rect.height = (sItem.y + sItem.height - rect.y);
					}
				}
				
				var gutter:Number = 20;
				
				rect.x -= gutter;
				rect.y -= gutter;
				rect.width += 2 * gutter;
				rect.height += 2 * gutter;
				
				return rect;
			}catch(err:Error){
				throw err;
			}
			return null;
		}
	}
}